<template>
  <div id="map" ref="mapContainer" class="h-[600px] w-full" />
  <button @click="showDebugInfo">显示调试信息</button>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from "vue";
import "leaflet/dist/leaflet.css";
import {
  mapFactoryByGeoq,
  mapFactoryByGaode,
  mapFactoryByBaidu,
  createGaodeTileLayer,
  createHeatmapLayer,
  cerateMarkerCluster
} from "@/utils/leaflet";

const mapContainer = ref(null);
let map: any = null;
let heatmapLayer: any = null;
// 示例热力图数据
let heatmapData = Array.from({ length: 10000 }, () => ({
  lng: 116.2 + Math.random() * 0.1,
  lat: 39.8 + Math.random() * 0.1,
  value: Math.random() * 100 // 字段名改为count
}));
onMounted(() => {
  // 初始化地图
  map = mapFactoryByGaode("map", {
    center: [39.9042, 116.4074],
    zoom: 10, // 增大缩放级别
    attributionControl: false, // 隐藏默认的版权信息
    tileType: "vector"
  });

  // 移除默认图层，添加高德矢量图层
  map.eachLayer(layer => map.removeLayer(layer));
  createGaodeTileLayer("vector").addTo(map);
  map.whenReady(() => {
    console.log("地图准备就绪，添加热力图");
    createGaodeTileLayer("vector").addTo(map);
    heatmapLayer = createHeatmapLayer(map, heatmapData);
    console.log("heatmapLayer", heatmapLayer);
    map.addLayer(heatmapLayer);
    map.setView([39.9042, 116.4074], 10); // 强制重置视图
  });
  // 添加容错机制
  setTimeout(() => {
    if (!map.hasLayer(heatmapLayer)) {
      console.warn("热力图加载超时，强制添加");
      heatmapLayer.addTo(map);
    }
  }, 3000);
  window.debugHeatmap = heatmapLayer; // 暴露到全局
  window.debugMap = map; // 暴露地图实例
});

// 添加组件卸载处理
onUnmounted(() => {
  if (heatmapLayer) {
    map.removeLayer(heatmapLayer);
    heatmapLayer = null;
  }
});
const showDebugInfo = () => {
  if (!heatmapLayer) return;

  console.log("图层状态:", {
    inMap: heatmapLayer._map !== null,
    dataPoints: heatmapLayer._heatmap.getData().data.length
  });

  const center = map.getCenter();
  console.log("地图中心:", [center.lat, center.lng]);
  console.log("数据范围:", heatmapLayer._heatmap);
};
</script>
<style scoped>
:deep(.leaflet-heatmap-layer) {
  pointer-events: none; /* 防止交互遮挡 */
  opacity: 0.9 !important; /* 覆盖默认透明度 */
}
</style>
